#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
day 28 homework
"""
# 1.基于tcp协议实现聊天基础需求：
# 1.server和client端连接之后，能知道对面这个人是哪一个好友 qq号
# 2.不同好友的聊天颜色不同 https://www.cnblogs.com/Eva-J/p/8330517.html
"""
import socket

sk = socket.socket()
sk.bind(('127.0.0.1', 9001))
sk.listen(20)
ls = [31, 32, 33, 34]
id_dict = dict()
while True:
    conn, addr = sk.accept()
    id = conn.recv(1024).decode('utf-8')
    if id not in id_dict:
        id_dict[id] = ls.pop(0)
    while True:
        msg = conn.recv(1024).decode('utf-8')
        if msg.upper() == 'Q':
            print('%s断开连接' % id)
            break
        print('\033[0;%sm%s:%s\033[0m' % (id_dict[id],id, msg))
"""
# 2.基于udp协议实现聊天需求
# 基础需求：
    # 能随时退出
    # 能实现一个人和多个人聊天
    # 并且给每个人标识一个身份
    # 每个身份一种颜色
# 进阶需求：（选做）
    # 多个人能同时互相聊
"""
import socket

sk = socket.socket(type=socket.SOCK_DGRAM)
sk.bind(('127.0.0.1', 9001))
ls = [31, 32, 33, 34]
id_dict = dict()
while True:
    id, client_addr = sk.recvfrom(1024)
    id = id.decode('utf-8')
    if id not in id_dict:
        id_dict[id] = ls.pop(0)
    while True:
        msg, client_addr = sk.recvfrom(1024)
        msg = msg.decode('utf-8')
        if msg.upper() == 'Q':
            print('%s断开连接' % id)
            break
        print('\033[0;%sm%s:%s\033[0m' % (id_dict[id],id, msg))
"""
# 3.基于tcp协议实现用户登陆
    # 基础 ：只实现基础的登陆即可
    # 进阶 ：加入hashlib密文存储密码
    # 密文摘要 在server端还是client端？
"""
import socket

sk = socket.socket()
sk.bind(('127.0.0.1', 9001))
sk.listen()
conn, addr = sk.accept()
user_dict = {'alex': '7d25c219d84c41f6ab70882b423bd8a5', 'admin': '71a8ea09a25d1343791b72123774157e'}
while True:
    user = conn.recv(1024).decode('utf-8')
    pwd = conn.recv(1024).decode('utf-8')
    if pwd == user_dict.get(user):
        conn.send('登录成功'.encode('utf-8'))
    else:
        conn.send('用户名或密码错误'.encode('utf-8'))
"""